package com.nxw.springcloud.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.chanjet.common.endpoint.pojo.ChanjetValueResult;
import com.nxw.springcloud.admin.entity.AppKeyAndSecret;
import com.nxw.springcloud.admin.entity.RateLimiterInfo;
import com.nxw.springcloud.admin.enums.EnvironmentEnum;
import com.nxw.springcloud.admin.respository.AppKeyAndSecretDao;
import com.nxw.springcloud.admin.respository.GatewayRateLimiterInfoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @program:
 * @description:
 * @author: nxw
 * @create: 2020-02-24 15:48
 **/
@RestController
@RequestMapping("/limitInfo")
public class RateLimiterInfoController {



    @Autowired
    GatewayRateLimiterInfoDao infoDao;

    @Autowired
    AppKeyAndSecretDao appKeyAndSecretDao;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping(value = "/add")
    public RateLimiterInfo addRata(@RequestBody RateLimiterInfo rateLimiterVO){
        redisTemplate.opsForHash().put(rateLimiterVO.getEnvironment().getValue(),rateLimiterVO.getAppKey()+"#"+rateLimiterVO.getAppSecret(), JSONObject.toJSONString(rateLimiterVO));
        return infoDao.save(rateLimiterVO);
    }

    @RequestMapping(value = "/get")
    public ChanjetValueResult<String> getRateLimiterVO(String appKey, EnvironmentEnum environment){

        RateLimiterInfo rateLimiterInfoByAppKey = infoDao.findRateLimiterInfoByAppKeyAndEnvironment(appKey,environment);
        if (rateLimiterInfoByAppKey == null){
            AppKeyAndSecret appKeyAndSecretByAppKey = appKeyAndSecretDao.findAppKeyAndSecretByAppKeyAndEnvironment(appKey,environment);
            if (appKeyAndSecretByAppKey !=null) {
                redisTemplate.opsForHash().put(appKeyAndSecretByAppKey.getEnvironment().getValue(),appKeyAndSecretByAppKey.getAppKey() + "#" + appKeyAndSecretByAppKey.getAppSecret(), "");
            }
            return null;
        }
        redisTemplate.opsForHash().put(rateLimiterInfoByAppKey.getEnvironment().getValue(),rateLimiterInfoByAppKey.getAppKey()+"#"+rateLimiterInfoByAppKey.getAppSecret(), JSONObject.toJSONString(rateLimiterInfoByAppKey));
        return ChanjetValueResult.success(JSONObject.toJSONString(rateLimiterInfoByAppKey));
    }

}
